package gsw.tool.skin;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.v4.view.LayoutInflaterCompat;
import android.view.LayoutInflater;

import java.lang.reflect.Field;
import java.util.HashMap;

import gsw.tool.skin.utils.SkinThemeUtils;


/**
 * Created by siwei on 2018/3/18.
 */

class SkinActivityLifeCallback implements Application.ActivityLifecycleCallbacks {
    //缓存activity与布局加载器
    HashMap<Activity, SkinLayoutFactory> skinLayoutFactorys = new HashMap<>();
    //状态栏的工厂
    SkinLayoutFactory statusBarFactory = null;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        initSkin(activity);
        initStatusBar(activity);
    }

    /**
     * 初始化状态栏
     *
     * @param activity
     */
    private void initStatusBar(Activity activity) {
        SkinThemeUtils.updateStatusBar(activity);
    }

    /**
     * 初始化：设置Factory2
     *
     * @param activity
     */
    private void initSkin(Activity activity) {
        //获取Activity的布局加载器
        LayoutInflater layoutInflater = LayoutInflater.from(activity);
        try {
            //将布局加载器的mFactorySet属性为false,这样就会使用Factory2来加载view
            Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
            field.setAccessible(true);
            field.setBoolean(layoutInflater, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        SkinLayoutFactory skinLayoutFactory = new SkinLayoutFactory(activity);
        //兼容低版本的写法:设置Factory2
        LayoutInflaterCompat.setFactory2(layoutInflater, skinLayoutFactory);
        //用于手动换肤
        SkinManager.getInstance().addObserver(skinLayoutFactory);
        skinLayoutFactorys.put(activity, skinLayoutFactory);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        //删除观察者
        SkinLayoutFactory skinLayoutFactory = skinLayoutFactorys.remove(activity);
        SkinManager.getInstance().deleteObserver(skinLayoutFactory);
    }
}
